package pers.cz.postgirl.core.common;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;

/**
 * @program: postgirl-client
 * @description: 重写ObjectInputStream中的resolveClass方法，
 * 使之可以使用不同的类加载器加载，如果不重写则使用的是appclassloader,
 * 使用appClassLoader去加载jar包中的类会抛出ClassNotFoundException
 * @author: Cheng Zhi
 * @create: 2023-08-09 10:54
 **/
public class ObjectInputStreamWithLoader extends ObjectInputStream {

    private ClassLoader loader;

    public ObjectInputStreamWithLoader(InputStream in, ClassLoader loader) throws IOException {
        super(in);
        if (loader == null) {
            throw new IllegalArgumentException("未找到类加载器");
        }

        System.out.println("当前使用的类加载为：" + loader.getClass().getName());
        this.loader = loader;
    }

    @Override
    protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {

        String cname = desc.getName();
        return Class.forName(cname, false, loader);
        // return loader.loadClass(cname);
    }
}
